package com.example.chatroom.api;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
//让spring感知到有这个类，注册到Spring中
@Component
public class TestWebSocketAPI extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //这个方法会在 websocket 连接成功后自动调用
        System.out.println("websocket 连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //这个方法会在 websocket 收到消息后，自动调用
        System.out.println("textAPI 收到消息"+message.toString());
        //session这个会话，里面记录了通信双方是谁，session中持有了websocket的通信连接
        session.sendMessage(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //这个方法会在连接出现异常后,自动调用
        System.out.println("textAPI 收到消息");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //这个方法会在正常关闭后,自动调用
        System.out.println("textAPI 收到消息");
    }
}
